#include "app_running.h"
#include <signal.h>
#include <unistd.h>

static int is_running = 1;

static void app_running_exit(void)
{
    is_running = 0;
}

void app_running_start(void)
{
    // ctrl + c kill
    signal(SIGINT, (void *)app_running_exit);
    signal(SIGTERM, (void *)app_running_exit);
    // 初始化线程池
    int ret = app_pool_init(THREAD_NUM);
    if (ret == 0)
    {
        log_info("线程池初始化成功");
    }
    
    ret = app_mqtt_init();
    if (ret == 0)
    {
        log_info("消息队列初始化成功");
    }
    // 初始化设备
    device_t *device = app_device_init(DEVICE_FILE);
    if (device != NULL)
    {
        log_info("设备初始化成功");
    }
    
    // 对设备结构体进行蓝牙设置
    ret = app_serial_init(device);
    if (ret == 0)
    {
        log_info("串口初始化成功");
    }
    ret = app_bt_init(device);
    if (ret == 0)
    {
        log_info("蓝牙初始化成功");
    }
    // 启动设备
    ret = app_device_start();
    if (ret == 0)
    {
        log_info("设备启动成功");
    }
    // 延时
    while (is_running)
    {
        sleep(1);
    }
    
    // 销毁设备
    app_device_destroy();
    app_pool_destroy();
    app_mqtt_destroy();
}